//
//  TimerBtn.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/19.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class TimerBtn: UIButton {
    var timer:Timer?
    var time:NSInteger = 0
    var nextTime = 0
    var titleStr = ""
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setTitle(kText("获取验证码"), for: UIControlState.normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        self.setTitleColor(kThemeColor, for: UIControlState.normal)
        self.titleLabel?.textAlignment = NSTextAlignment.center
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func timeStart() -> Void {
        if time == 0 {
            time = 60
        }
        nextTime = time
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeFireMethod), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)
        self.isEnabled = false
    }
    
    @objc func timeFireMethod() -> Void {
        nextTime = nextTime - 1
        if titleStr.count == 0  {
            self.setTitle(String(format: kText("剩余%d秒"),nextTime), for: UIControlState.normal)
            
        }else {
           self.setTitle(String(format: "%ld%@",nextTime,titleStr), for: UIControlState.normal)
        }
        self.themeSetTitleColor(ThemeManager.ThemeColorKeys.text1, for: UIControlState.normal)
        self.titleLabel?.textAlignment = NSTextAlignment.center
        
        if nextTime <= 0 {
            self.setTitle(kText("获取验证码"), for: UIControlState.normal)
            self.isEnabled = true
            self.setTitleColor(kThemeColor, for: UIControlState.normal)
            timer?.invalidate()
        }
        
    }
    
    func invlidateTimer() -> Void {
        timer?.invalidate()
        timer = nil
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
